package client

import (
	"common/initialization"
	"context"
	"fmt"
	"google.golang.org/grpc"
	user "user_srv/proto"
)

type UserHandler func(ctx context.Context, client user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler UserHandler) (interface{}, error) {
	cf := initialization.Config.UserServer
	dial, err := grpc.Dial(fmt.Sprintf("%s:%d", cf.Hort, cf.Port), grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	return handler(ctx, client)
}

func UserLogin(ctx context.Context, req *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.UserLogin(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResponse), nil
}
func OrderList(ctx context.Context, req *user.OrderListRequest) (*user.OrderListResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.OrderList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.OrderListResponse), nil
}
func UserCouponList(ctx context.Context, req *user.UserCouponListRequest) (*user.UserCouponListResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.UserCouponList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserCouponListResponse), nil
}
func CouponAdd(ctx context.Context, req *user.CouponAddRequest) (*user.CouponAddResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.CouponAdd(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.CouponAddResponse), nil
}
func CouponList(ctx context.Context, req *user.CouponListRequest) (*user.CouponListResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.CouponList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.CouponListResponse), nil
}

func UserIntegralChange(ctx context.Context, req *user.UserIntegralChangeRequest) (*user.UserIntegralChangeResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, client user.UserClient) (interface{}, error) {
		login, err := client.UserIntegralChange(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserIntegralChangeResponse), nil
}
